package com.eqdd.yiqidian.ui.mine.maker.fragment

import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.MakerMessageBean
import com.eqdd.yiqidian.box.ItemDecoration.DividerLineItemDecoration
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource
import com.eqdd.yiqidian.http.DialogCallBack
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.http.JsonConverter
import com.eqdd.yiqidian.kotlin.deleteDialog
import com.eqdd.yiqidian.kotlin.toArrayList
import com.eqdd.yiqidian.ui.base.EditTextActivity
import com.eqdd.yiqidian.ui.mine.UserCardActivity
import com.eqdd.yiqidian.ui.mine.maker.OwnerMakerSpaceActivity
import com.eqdd.yiqidian.utils.TimeUtil
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import com.lzy.okrx2.adapter.FlowableBody
import com.shizhefei.mvc.MVCCoolHelper
import io.reactivex.Flowable
import kotlinx.android.synthetic.main.fragment_company_space.view.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.support.v4.startActivity
import org.jetbrains.anko.support.v4.startActivityForResult
import org.jetbrains.anko.support.v4.toast
import java.util.*

/**
 * Created by jhj on 18-7-4.
 */
class MakerMessageFragment : Fragment() {

    private var mvcHelper: MVCCoolHelper<List<MakerMessageBean>>? = null
    private var userCompanyId: Int? = null
    private var userGuid: String? = null
    private var makerGuid: String? = null


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_company_space, container, false)
        initView(view)
        return view
    }


    private fun initView(view: View) {
        view.layout_add.visibility = View.VISIBLE
        view.tv_add.onClick {
            startActivityForResult<EditTextActivity>(1000, "title" to "留言", "tip" to "留言")
        }
        view.recyclerView.layoutManager = LinearLayoutManager(activity)
        view.recyclerView.addItemDecoration(DividerLineItemDecoration(activity))
        var pageNum = 0
        userCompanyId = arguments?.getInt("userCompanyId", -1)
        userGuid = arguments?.getString(Config.GUID)
        makerGuid = arguments?.getString("makerGuid")
        mvcHelper = MVCCoolHelper<List<MakerMessageBean>>(view.coolRefreshView)
        val list = arrayListOf<MakerMessageBean>()
        val slimAdapterEx = SlimAdapterEx.create()
                .register<MakerMessageBean>(R.layout.list_item_161, SlimInjector<MakerMessageBean> { data, injector ->
                    injector?.text(R.id.tv_name, data?.staffName)
                            ?.text(R.id.tv_depart, String.format(Locale.CHINA, "%s - %s", data?.departName, data?.postName))
                            ?.text(R.id.tv_time, TimeUtil.formatWebTime(data?.createTime))
                            ?.imageCircle(R.id.iv_photo, data?.iphoto)
                            ?.text(R.id.tv_message, data?.message)
                            ?.with<RecyclerView>(R.id.recyclerView) {
                                it.layoutManager = LinearLayoutManager(activity)
                                SlimAdapterEx.create().register<MakerMessageBean>(R.layout.list_item_162, SlimInjector<MakerMessageBean> { t1, t2 ->
                                    t2?.text(R.id.tv_reply, "创客回复：" + t1?.message)
                                            ?.gone(R.id.tv_label)
                                }).attachTo(it).updateData(data?.childList?.toArrayList() as List<MakerMessageBean>)
                            }
                            ?.clicked(R.id.iv_photo) {
                                data?.creater?.let {
                                    startActivity<UserCardActivity>(Config.GUID to it)
                                }
                            }
                })
                .attachTo(view.recyclerView)
                .updateData(list as List<MakerMessageBean>?) as SlimAdapterEx<MakerMessageBean>?
        ItemClickSupport.addTo(view.recyclerView)
                .setOnItemLongClickListener { recyclerView, position, v ->
                    val data = slimAdapterEx?.getDataItem(position)
                    if (data?.creater == userGuid) {
                        (activity as? OwnerMakerSpaceActivity)?.deleteDialog(HttpConfig.BASE_URL + HttpConfig.MESSAGE_DELETE, "是否删除“${data?.message}”？", "type" to 1, "msgId" to data?.id, isFinish = false) {
                            slimAdapterEx?.data?.removeAt(position)
                            slimAdapterEx?.notifyItemRemoved(position)
                        }
                    }
                    true
                }
        val dataSource = ModelRx2DataSource<MakerMessageBean>(ModelRx2DataSource.OnLoadSource<MakerMessageBean> { page, register ->
            if (page == 1) {
                pageNum = 0
            }
            OkGo.post<HttpResult<List<MakerMessageBean>>>(HttpConfig.BASE_URL + HttpConfig.MESSAGE_GET)
                    .params("makerGuid", makerGuid)
                    .params("page", pageNum)
                    .converter(object : JsonConverter<HttpResult<List<MakerMessageBean>>>() {
                        override fun test() {
                            super.test()
                        }
                    }).adapt(FlowableBody<HttpResult<List<MakerMessageBean>>>())
                    .flatMap({ result ->
                        if (page == 1) {
                            mvcHelper?.isAutoLoadMore = true
                        }
                        pageNum = result.page
                        Flowable.just<MutableList<MakerMessageBean>>(
                                if (result.items == null)
                                    ArrayList()
                                else
                                    result.items as MutableList<MakerMessageBean>?)
                    })
        }, 10)


        mvcHelper?.setDataSource(dataSource)
        mvcHelper?.adapter = slimAdapterEx
        mvcHelper?.refresh()
    }


    private fun leaveMessage(msg: String) {
        OkGo.post<HttpResult<MakerMessageBean>>(HttpConfig.BASE_URL + HttpConfig.MESSAGE_ADD)
                .params("userGuid", userGuid)
                .params("userCompanyId", userCompanyId ?: 0)
                .params("message", msg)
                .params("parentId", 0)
                .params("parentUserGuid", 0)
                .params("firstCommentId", 0)
                .params("makerGuid", makerGuid)
                .params("objectId", 0)
                .params("objectType", 0)
                .execute(object : DialogCallBack<HttpResult<MakerMessageBean>>(activity) {
                    override fun onSuccess(response: Response<HttpResult<MakerMessageBean>>?) {
                        val result = response?.body()
                        if (result?.status == 200) {
                            mvcHelper?.refresh()
                        } else {
                            toast(result?.msg ?: "")
                        }
                    }

                })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Config.INTENT_CONTENT) {
            when (requestCode) {
                1000 -> {
                    val str = data?.getStringExtra(Config.CONTENT)
                    leaveMessage(str ?: "")
                }
            }
        }

    }


}